<?php
/**
* 程序入口控制器，主要是控制权限
* ex-chendeng001
*/

class ctrl_base extends framework_base_ctrl {

	//分页控制信息
    protected static $_pagesize = 20;
	protected static $_shoNum = array(20,50,100,200,300);
	protected static $_pageNumShown = 10;
	//最大微信openid 个数
	protected static $_max_wechat_ID = 5;
	protected static $_wechat_separe = "#";
	//特级管理员,不需要权限验证的
	protected static $_supper_auth = array('admin');
	//表格头个数
	protected static $_depth_num = 6;
	//文件导出类型
	protected static $_excel_pre = '.xls';
	//运输方式
	protected static $_transport = array(
		'area_price'=>array('name'=>'区域定价','id'=>1),
		'motor'=>array('name'=>'汽运','id' => 2),
		'motor_shipping'=>array('name'=>'水汽联运','id'=>3),
		'shipping'=>array('name'=>'船运','id'=>4),
		'train'=>array('name'=>'火运','id'=>5)
	);
	//字母字典列表
	protected static $words = array(
		'A'=>array(),'B'=>array(),'C'=>array(),'D'=>array(),'E'=>array(),'F'=>array(),'G'=>array(),
		'H'=>array(),'I'=>array(),'J'=>array(),'K'=>array(),'L'=>array(),'M'=>array(),'N'=>array(),
		'O'=>array(),'P'=>array(),'Q'=>array(),'R'=>array(),'S'=>array(),'T'=>array(),'U'=>array(),
		'V'=>array(),'W'=>array(),'X'=>array(),'Y'=>array(),'Z'=>array()
	);
    /*
     * 程序入口控制器
     * 
     * */
    public static function init() {
		//$preg = '/(admin_main)|(admin_check_code)|(admin_do_login)|(admin_adminLogin)/';
		//$str = $_GET['act'].'_'.$_GET['st'];//self::ajax_ouput(300,'您没有该权限，请联系管理员！');
		//if(!preg_match($preg, $str)){}
    }


    /**
     * Enter description here ...
     * @param string $url
     * @param array $param
     * @param string $dataType
     * @param array $header
     * @param string $method
     */
    protected static function curl($url, $param,$dataType = '', $header = array(), $method = 'POST') {
        $curl = new framework_base_curl();
        $curl->url = $url;
        $curl->method = $method;
        $curl->params = $param;
        $curl->headers = $header;
        $curl->exec();
        if($dataType == 'json'){
            $rs_curl = $curl->outputJson(true);
        } else {
            $rs_curl = $curl->result;
        }
        return  $rs_curl;
    }
    /**
     * 去登录界面
     */
    public static function goto_login() {    	
		self::ajax_ouput(301, '登录超时,请重新登录');
    }
    
    public static function redirect($url='') {
    	$url = $url !=''? $url:HOST_URL;
    	echo "<script>window.location.href='".$url."';</script>";
    	exit;
    }

	/**
	* @desc 获取请求数据
	* @param void
	* @return array()
	**/
	protected static function get_request_data(){
		$request = $_POST;
		$return = array();
		if(empty($request) || !is_array($request)){
			return $return;
		}
		foreach($request as $key => $value){
			if(!is_array($value)){
				$value = trim($value);
				$return[$key] = $value;
			}else{
				$return[$key] = $value;
			}
			
		}
		return $return;
	}

	/**
	  *ajax输出json函数
	  *@author kevin wang
	  */
	protected static function ajax_ouput($statusCode, $message, $navTabId = "", $callbackType = "", $forwardUrl = ""){
		$return = array(
			'statusCode'=>$statusCode,
			'message'=>$message,
			'callbackType'=>$callbackType,
			'navTabId'=>$navTabId,
			'forwardUrl'=>$forwardUrl
			);
		framework_static_function::output_json($return, false);
	}
	//xls文件上传
	protected static function file_upload_xls(){
		$config = array(
    				"savePath" => UPLOAD_FILES_PATH,
    				"maxSize" => 1024*10,
    				"allowFiles" => array(".xls",".xlsx",".csv")
    		);
		//文件上传
    	$up = new framework_static_uploader("Filedata", $config);
    	$info = $up->getFileInfo();
		if($info['state'] != 'SUCCESS'){
			self::ajax_ouput(300, $info['state']);
    		//framework_static_function::output_json($info, false);
    	}
		return $info;
	}
	//获取现在保存地址
	protected static function get_down_file_url($pre){
		$path = PATH_WWW.DOWNLOAD_FILES_PATH.date("Y")."/".date("m")."/".date("d")."/";
		framework_static_function::mkdirs($path);
		$file_name = (microtime(true)*10000).$pre;
		return array(
			'save' => $path.$file_name,
			'down' => $file_name);
	}
	//输出下载
	protected static function download_xls_output($file_path, $file_name=""){
		$arr = explode('.',$file_path);
		$count = count($arr);
		$time = microtime(true)*10000;
		$file_name = empty($file_name)?"{$time}.{$arr[$count-1]}":$file_name;
		ob_end_clean();
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
		header("Content-Type:application/force-download");
		header('Content-Type:application/vnd.ms-excel;charset=utf8');
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
		header("Content-Disposition:attachment;filename={$file_name}");
		header('Cache-Control: max-age=0');
		echo file_get_contents($file_path);exit;
	}
	//查找子类ID
	protected static function findChild(&$arr,$id){
		$childs=array();
		 foreach ($arr as $k => $v){
			 if($v['parentid']== $id){
				  $childs[]=$v;
			 }
		}
		return $childs;
		
		
	}
	//构建无限分类树
	protected static function build_tree($rows, $root_id){
		$childs=self::findChild($rows,$root_id);
		if(empty($childs)){
			return null;
		}
	   foreach ($childs as $k => $v){
		   $rescurTree=self::build_tree($rows,$v['id']);
		   if( null !=   $rescurTree){
				$childs[$k]['childs']=$rescurTree;
		   }
	   }
		return $childs;
	}
	//权限控制方法
	protected static function operation(array $authes){
		$username = $_SESSION['admin']['username'];
		if(in_array($username,self::$_supper_auth)){
			return true;
		}
		if(empty($authes)){
			self::ajax_ouput(300,'该功能已限制访问，请联系管理员！');
		}
		$auth = model_user::get_user_authes($_SESSION['admin']['userid']);
		if(empty($auth)){
			self::ajax_ouput(300,'您没有相关访问权限，请联系管理员！');
		}
		$arr = array();
		foreach($auth as $v){
			$arr[$v['ctrl_tag']] = $v['auth_id'];
		}
		foreach($authes as $v){
			if(!isset($arr[$v])){
				$name = model_user::get_auth_name($v);
				if(!empty($name)){
					self::ajax_ouput(300,"您没有 {$name} 权限，请联系管理员！", "", "closeCurrent");
				}
			}
		}
	}
	//是否特级权限
	protected static function supper_auth($username){
		return in_array($username,self::$_supper_auth);
	}
	//微信ID个数限制
	protected static function limit_weixin_id($weixin_id){
		if(empty($weixin_id)){
			self::ajax_ouput(300, '操作失败,微信ID不能为空');
		}
		$order_arr = explode(self::$_wechat_separe, $weixin_id);
		if(count($order_arr) > self::$_max_wechat_ID){
			self::ajax_ouput(300, '操作失败,微信ID最多5个');
		}
	}
	//统计数组子类个数
	protected static function count_array_childs($arr){
		if(empty($arr)){
			return $arr;
		}
		foreach($arr as $key => $value){
			$count = 0;
			if(!empty($value['childs']))
			foreach($value['childs'] as $k => $v){
				$co = count($v['childs']) + 1;
				$count += $co;
				$depth = $arr[$key]['childs'][$k]['depth'];
				$arr[$key]['childs'][$k]['count'] = $co;
				$arr[$key]['childs'][$k]['depth'] = self::$_depth_num - $depth;
				if(!empty($v['childs']))
				foreach($v['childs'] as $k_ => $v_){
					$depth = $arr[$key]['childs'][$k]['childs'][$k_]['depth'];
					$arr[$key]['childs'][$k]['childs'][$k_]['depth'] = self::$_depth_num - $depth;
				}
			}
			$arr[$key]['count'] = $count + 1;
		}
		return $arr;
	}
	//拆分用户分类数据
	protected static function analyze_user_category($str){
		$return = array();
		if(empty($str)){
			return $return;
		}
		$arr = explode(',',$str);
		foreach($arr as $key => $value){
			$arrs = explode('_', $value);
			$return[] = $arrs[1];
		}
		return $return;
	}

	//获取运输方式名称
	protected static function get_transport_name($id){
		foreach(self::$_transport as $v){
			if($id == $v['id']){
				return $v['name'];
			}
		}
		return '';
	}
	//处理权限分类
	protected static function handle_category(){
		$parents = $_POST['parent_id'];
		$result = "";
		if(!is_array($parents)){
			return $result;
		}
		$num = 0;
		foreach($parents as $key => $value){
			$varr = $_POST["category_{$value}"];
			$num += count($varr);
			if(is_array($varr)){
				foreach($varr as $v){
					$result .= "{$value}_{$v},";
				}
			}
		}
		if($num == 11){
			$result = "*_*";
		}
		$result = trim($result, ",");
		return $result;
	}
	//表格字段
	protected static function create_table_data($arr){
		$return = $arr;
		if(empty($arr)){
			return $return;
		}
		$basic_price[0][0] = '第一级字段';
		$basic_price[0][1] = '第二级字段';
		$basic_price[0][2] = '第三级字段';
		$basic_price[0][3] = '上期价格';
		$basic_price[0][4] = '当前价格';
		$basic_price[0][5] = '调整幅度';
		$count = 0;
		$carr[] = 'range';
		$carr[] = 'range';
		$carr[] = 'range';
		foreach($arr['basic_price'] as $value){
			$i = 0;
			$co = count($value['marerial']);
			$count += $co;
			$value['count'] = $co;
			foreach($value as $k => $v){
				if($k == "count"){
					$basic_price[$i][count($basic_price[3]) + 1] = $v;
				}else{
					$basic_price[$i][] = $v;
				}
				$i++;
			}
			if(!empty($value['marerial'])){
				foreach($value['marerial'] as $v){
					$carr[] = $v;
				}
			}
		}
		//$return['basic_count_num'] = $count;
		//$return['basic_count'] = $basic_price[3];
		$return['basic_count_arr'] = $carr;
		//$return['basic_count_js'] = json_encode($carr);
		unset($basic_price[3]);
		$return['basic_price'] = $basic_price;
		/*$transport = array();
		if(!empty($arr['area_price'])){
			foreach($arr['area_price'] as $v){
				$transport_id = $v['transport_id'];
				$transport_name = self::get_transport_name($transport_id);
				$v['area_id'] = 'trans'.$v['transport_id'].$v['area_id'];
				$transport[$transport_name][] = $v;
			}
		}*/
		//$return['transport'] = $transport;
		return $return;
	}
	//组织表格数据
	protected static function create_table_contain($arr){
		$return = array();
		if(empty($arr)){
			return $return;
		}
		//$return['price_data_js'] = json_encode(array());
		if(!empty($arr['price_data'])){
			foreach($arr['price_data'] as $value){
				//$forarr = json_decode($value['attr_value'], true);
				$return['price_data'][$value['attr_id']] = $value[0];
			}
			//$return['price_data_js'] = json_encode($return['price_data']);
		}
		
		/*if(!empty($arr['transport_data']))
		foreach($arr['transport_data'] as $value){
			$return['transport_data'][$value['attr_id']] = json_decode($value['attr_value'], true);
		}*/
		return $return;
	}
}